package com.laoxu.java.multithread;

import java.util.concurrent.locks.StampedLock;

/**
 *
 * StampedLock把读锁细分为乐观读和悲观读，能进一步提升并发效率。
 * 但这也是有代价的：一是代码更加复杂，二是StampedLock是不可重入锁，不能在一个线程中反复获取同一个锁。
 *
 * 如果您需要更高的性能和更好的灵活性，那么StampedLock可能是一个更好的选择。
 * 但是，如果您只需要一个简单的读写锁，并且不需要额外的功能，那么ReadWriteLock仍然是一个不错的选择。
 *
 */
public class StampedLockExample {
    private int count = 0;
    private final StampedLock stampedLock = new StampedLock();

    public void increment() {
        long stamp = stampedLock.writeLock();
        try {
            count++;
            System.out.println("当前计数：" + count);
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }

    public void decrement() {
        long stamp = stampedLock.writeLock();
        try {
            count--;
            System.out.println("当前计数：" + count);
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }

    public void read() {
        long stamp = stampedLock.tryOptimisticRead();
        int currentCount = count;
        if (!stampedLock.validate(stamp)) {
            stamp = stampedLock.readLock();
            try {
                currentCount = count;
            } finally {
                stampedLock.unlockRead(stamp);
            }
        }
        System.out.println("当前计数：" + currentCount);
    }

    public static void main(String[] args) {
        StampedLockExample example = new StampedLockExample();

        // 创建10个读线程和2个写线程
        for (int i = 0; i < 10; i++) {
            new Thread(example::read).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(example::increment).start();
            new Thread(example::decrement).start();
        }
    }
}
